<?php
/**
*By∶云猫
*域名/ssl.php?domain=要检测的域名
*Blog∶lwcat.cn
**/
function getSSLCertificateExpiry($domain) {
    $get = stream_context_create([
        "ssl" => [
            "capture_peer_cert" => TRUE,
            "verify_peer"       => FALSE,
            "verify_peer_name"  => FALSE,
        ],
    ]);

    $read = @stream_socket_client(
        "ssl://{$domain}:443",
        $errno, $errstr, 30, STREAM_CLIENT_CONNECT, $get
    );

    if ($read === FALSE) {
        return ["error" => "Unable to connect to {$domain}"];
    }

    $cert = stream_context_get_params($read);
    $certinfo = openssl_x509_parse($cert['options']['ssl']['peer_certificate']);

    if (!$certinfo) {
        return ["error" => "Unable to parse the certificate"];
    }

    $validTo = date('Y-m-d H:i:s', $certinfo['validTo_time_t']);
    
    return ["domain" => $domain, "valid_to" => $validTo];
}

if ($_SERVER['REQUEST_METHOD'] === 'GET' && isset($_GET['domain'])) {
    $domain = $_GET['domain'];
    $result = getSSLCertificateExpiry($domain);
    header('Content-Type: application/json');
    echo json_encode($result);
} else {
    echo json_encode(["error" => "Please provide a domain parameter"]);
}